<?php

namespace Forwzb\Yii2Api\api;

use Yii;
use yii\base\BootstrapInterface;

/**
 * api预置设置
 *
 * 包含：
 * ```
 * corsFilter 跨域
 * baseAuth 认证
 * contentNegotiator 响应格式和语言
 * ```
 */
class ApiPresetBootstrap implements BootstrapInterface
{
    public array|false $corsFilter = [];
    public array|false $basicAuth = [];
    public array|false $contentNegotiator = [];
    public $initBootstrap = null;

    /** @var \yii\web\Application $app */
    public function bootstrap($app)
    {
        if (is_callable($this->initBootstrap)) {
            $fun = $this->initBootstrap;
            call_user_func($fun,$app);
        }

        if ($this->corsFilter !== false) {
            $app->attachBehavior('corsFilter', [
                'class' => \yii\filters\Cors::class,
                ...$this->corsFilter
            ]);
        }
        if ($this->contentNegotiator !== false) {
            $app->attachBehavior('contentNegotiator', [
                'class' => \yii\filters\ContentNegotiator::class,
                ...$this->contentNegotiator
            ]);
        }
        if ($this->basicAuth !== false) {
            $app->attachBehavior('basicAuth', [
                'class' => \yii\filters\auth\HttpBearerAuth::class,
                ...$this->basicAuth
            ]);
        }
    }

    /**
     * 注入常规配置，根据项目需要修改
     */
    public static function injectionConfig(): void
    {
        \Yii::$container->set('yii\data\Pagination', [
            'pageParam' => 'current',
            'pageSizeParam' => 'pageSize',
        ]);

        \Yii::$container->set('yii\rest\Serializer', [
            'class' => 'Forwzb\Yii2Api\serializer\DataSerializer',
            'collectionEnvelope' => 'data',
        ]);
    }
}